<template>
  <div class="silo-management">
    <div class="page-title">筒仓管理</div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="筒仓编码">
          <el-input v-model="searchForm.siloCode" placeholder="请输入筒仓编码" clearable />
        </el-form-item>
        <el-form-item label="筒仓名称">
          <el-input v-model="searchForm.siloName" placeholder="请输入筒仓名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 150px" clearable>
            <el-option label="启用" value="10" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon> 新增筒仓
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-card>
      <el-table :data="siloList" stripe v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" v-if="false"/>
        <el-table-column prop="siloCode" label="筒仓编码" />
        <el-table-column prop="siloName" label="筒仓名称" />
        <el-table-column prop="materCode" label="物料编码" />
        <el-table-column prop="materName" label="物料名称" />
        <el-table-column prop="minStockQty" label="最低安全库存" />
        <el-table-column prop="maxStockQty" label="最高安全库存" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="capacityQty" label="额定容量">
          <template #default="scope">
            {{ scope.row.capacityQty }} {{ scope.row.unit }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === '10' ? 'success' : 'danger'">
              {{ scope.row.status === '10' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="warehouseName" label="仓库名称" />
        <el-table-column prop="locationName" label="库位名称" /> 
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 筒仓表单弹窗 -->
    <SiloForm
      :visible="siloFormVisible"
      @update:visible="siloFormVisible = $event"
      :form-data="siloFormData"
      @submit="handleFormSubmit"
      @close="handleFormClose" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { request } from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

// 导入组件
import SiloForm from './SiloForm.vue'

// 响应式数据
const loading = ref(false)
const siloList = ref([])
const siloFormVisible = ref(false)

// 搜索表单
const searchForm = reactive({
  siloCode: '',
  siloName: '',
  status: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 筒仓表单数据
const siloFormData = reactive({
  id: '',
  siloCode: '',
  siloName: '',
  materCode: '',
  materName: '',
  warehouseID: '',
  warehouseName: '',
  locationID: '',
  locationName: '',
  unit: '',
  capacityQty: null,
  capacityvolumeM3: null,
  minStockQty: null,
  maxStockQty: null,
  reorderPointQty: null,
  manufacturer: '',
  model: '',
  serialNo: '',
  installDate: '',
  status: '10',
  remarks: ''
})

// 加载筒仓数据
const loadSiloData = async () => {
  loading.value = true
  try {
    const params = {
      filter: {
        pageIndex: pagination.current,
        pageSize: pagination.size,
        orderBy: "createTime",
        isAscending: true
      },
      siloInfo: {
        ...searchForm
      }
    }
    
    // 调用后端API
    const response = await request.post('/SiloInfo/SiloPage', params)
    siloList.value = response.data
    pagination.total = response.totalCount
  } catch (error) {
    ElMessage.error('加载筒仓数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadSiloData()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.current = 1
  loadSiloData()
}

// 新增筒仓
const handleAdd = () => {
  // 重置表单数据
  Object.keys(siloFormData).forEach(key => {
    siloFormData[key] = ''
  })
  siloFormData.status = '10'
  
  siloFormVisible.value = true
}

// 编辑筒仓
const handleEdit = (row) => {
  // 填充表单数据
  Object.keys(siloFormData).forEach(key => {
    if (row[key] !== undefined && row[key] !== null) {
      siloFormData[key] = row[key]
    }
  })
  
  siloFormVisible.value = true
}

// 删除筒仓
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除筒仓 "${row.siloName}" 吗？`, '提示', {
      type: 'warning'
    })
    
    // 调用删除API
    await request.delete(`/SiloInfo/DeleteSilo/${row.id}`)
    ElMessage.success('删除成功')
    loadSiloData()
    
  } catch (error) {
    console.log('删除取消或失败')
  }
}

// 表单提交处理
const handleFormSubmit = async (formData) => {
  try {
    if (formData.id) {
      // 编辑筒仓
      await request.post('/SiloInfo/SiloSave', formData)
      ElMessage.success('更新成功')
    } else {
      // 新增筒仓
      await request.post('/SiloInfo/SiloSave', formData)
      ElMessage.success('创建成功')
    }
    
    siloFormVisible.value = false
    loadSiloData()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 表单关闭处理
const handleFormClose = () => {
  // 可以在这里添加关闭后的清理逻辑
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadSiloData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.current = page
  loadSiloData()
}

// 页面加载时获取数据
onMounted(() => {
  loadSiloData()
})
</script>

<style scoped>
.silo-management {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}
</style>